import axios from 'axios'
import { Loading, Message } from 'element-ui'
// import router from '@/router'
const request = axios.create({
  // baseURL: 'http://192.168.111.45:8080'
  // baseURL: 'http://192.168.111.32:8080'
  baseURL: 'http://47.115.201.19:8080'
})
axios.defaults.withCredentials = true
let loadingInstance = null
// 配置请求拦截器
request.interceptors.request.use(
  (config) => {
    // 声明token认证字段
    config.headers.token = `${localStorage.getItem('token')}`
    // config.headers.Authorization = 'Bearer xxx'
    if (localStorage.token) {
      // 判断token是否存在
      config.headers.Authorization = localStorage.token // 将token设置成请求头
    }
    // 开启loding效果
    loadingInstance = Loading.service({
      fullscreen: true,
      text: '正在努力加载中'
    })
    return config
  },
  (error) => {
    loadingInstance.close()
    Message.error({
      message: '加载超时'
    })
    return Promise.reject(error)
  }
)

// 配置响应拦截器
request.interceptors.response.use(
  (response) => {
    const res = response.data
    // if (res.code === 608) {
    //   Message({
    //     showClose: true,
    //     message: '登录失效,请重新登录',
    //     type: 'error'
    //   })
    //   setTimeout(() => {
    //     window.location.href = '/homestay'
    //   }, 2000)
    // }
    // 关闭loading效果 // 以服务的方式调用的 Loading 需要异步关闭
    loadingInstance.close()
    return response
  },
  (error) => {
    loadingInstance.close()
    Message.error({
      message: '加载失败'
    })
    return Promise.reject(error)
  }
)
export default request
